import tkinter as tk
from tkinter import ttk, messagebox, simpledialog

from pymysql import IntegrityError

from ttk_view_logic.view_logic import view_logic


class SimpleGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("职工信息管理系统")
        self.logic = view_logic()

        # 创建主界面
        self.create_main_frame()
        self.create_menu_bar()

    def create_main_frame(self):
        """创建主工作区"""
        self.main_frame = ttk.Frame(self.root, padding=10)
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def create_menu_bar(self):
        """创建顶部菜单"""
        menu_bar = tk.Menu(self.root)

        # 功能菜单
        func_menu = tk.Menu(menu_bar, tearoff=0)
        for idx, (text, func) in enumerate([
            ("1. 信息录入", self.open_input_dialog),
            ("2. 信息浏览", self.show_browse_window),
            ("3. 信息查询", self.open_search_dialog),
            # ("4. 信息排序", self.show_sort_result),
            # ("5. 信息删除", self.open_delete_dialog),
            # ("6. 信息修改", self.open_update_dialog),
            ("7. 退出系统", self.exit_system)
        ], 1):
            func_menu.add_command(label=text, command=func)
            if idx % 2 == 0:
                func_menu.add_separator()

        menu_bar.add_cascade(label="功能菜单", menu=func_menu)
        self.root.config(menu=menu_bar)

    # ================= 功能实现 =================
    def open_input_dialog(self):
        """打开信息录入对话框"""

        class InputDialog(simpledialog.Dialog):
            def __init__(self, parent, logic, **kwargs):
                self.logic = logic
                super().__init__(parent, **kwargs)

            def body(self, master):
                """创建界面控件"""
                self.fields = {}

                # 工号（必填）
                ttk.Label(master, text="工号：").grid(row=0, column=0, sticky=tk.W)
                self.fields["employee_id"] = ttk.Entry(master)
                self.fields["employee_id"].grid(row=0, column=1)

                # 姓名（必填）
                ttk.Label(master, text="姓名：").grid(row=1, column=0, sticky=tk.W)
                self.fields["name"] = ttk.Entry(master)
                self.fields["name"].grid(row=1, column=1)

                # 年龄（数字）
                ttk.Label(master, text="年龄：").grid(row=2, column=0, sticky=tk.W)
                self.fields["age"] = ttk.Entry(master)
                self.fields["age"].grid(row=2, column=1)

                # 性别（下拉选择）
                ttk.Label(master, text="性别：").grid(row=3, column=0, sticky=tk.W)
                self.fields["gender"] = ttk.Combobox(master, values=["男", "女"])
                self.fields["gender"].grid(row=3, column=1)

                # ...其他字段（教育/工资/地址/电话）...

                return self.fields["employee_id"]  # 初始焦点

            def validate(self):
                """前端验证"""
                # 必填字段检查
                for key in ["employee_id", "name", "age", "gender"]:
                    if not self.fields[key].get().strip():
                        messagebox.showerror("错误", f"{self.get_label(key)}不能为空")
                        return False

                # 年龄范围验证
                try:
                    age = int(self.fields["age"].get())
                    if not (1 <= age <= 65):
                        raise ValueError
                except ValueError:
                    messagebox.showerror("错误", "年龄必须是1-65之间的整数")
                    return False

                return True

            def apply(self):
                """收集数据并调用业务逻辑"""
                emp_data = {
                    "employee_id": self.fields["employee_id"].get().strip(),
                    "name": self.fields["name"].get().strip(),
                    "age": int(self.fields["age"].get()),
                    "gender": self.fields["gender"].get(),
                    "education": self.fields["education"].get().strip(),
                    "salary": int(self.fields["salary"].get()),
                    "address": self.fields["address"].get().strip() or None,
                    "phone_number": self.fields["phone_number"].get().strip() or None
                }

                try:
                    self.logic.emp_input(emp_data)
                    messagebox.showinfo("成功", "信息录入成功！")
                except (ValueError, IntegrityError) as e:
                    messagebox.showerror("错误", str(e))
                except Exception as e:
                    messagebox.showerror("系统错误", f"发生未知错误：{str(e)}")

        # 创建并显示对话框（修正参数传递）
        dialog = InputDialog(self.root, logic=self.logic, title="信息录入")
        dialog.mainloop()

    def show_browse_window(self):
        """显示浏览窗口"""

        class BrowseWindow(tk.Toplevel):
            def __init__(self, master):
                super().__init__(master)
                self.title("信息浏览")
                self.tree = ttk.Treeview(self, columns=("ID", "姓名", "年龄"), show="headings")

                # 加载数据
                data = self.logic.emp_Browse()
                for row in data:
                    self.tree.insert("", tk.END, values=row[:3])  # 示例显示前3列

                self.tree.pack(fill=tk.BOTH, expand=True)

        BrowseWindow(self.root).logic = self.logic

    # 其他功能类似实现（示例简化）
    def open_search_dialog(self):
        target = simpledialog.askstring("查询", "输入查询内容：")
        if target:
            try:
                result = self.logic.emp_select(target)
                messagebox.showinfo("查询结果", f"找到{len(result)}条记录")
            except Exception as e:
                messagebox.showerror("错误", str(e))

    def exit_system(self):
        self.root.quit()

    # ================= 辅助方法 =================
    def show_message(self, title, message):
        messagebox.showinfo(title, message)


if __name__ == "__main__":
    root = tk.Tk()
    app = SimpleGUI(root)
    root.mainloop()